package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"yktwo/models/redis"
	"yktwo/pkg"
	"yktwo/yktworpc/internal/svc"
	"yktwo/yktworpc/yktworpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 短信
func (l *SendSmsLogic) SendSms(in *yktworpc.SendSmsRequest) (*yktworpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	Intn := rand.Intn(9000) + 1000

	get := redis.Client.Get("sendSmsMinute" + in.Mobile + in.Source)

	if get.Val() >= "1" {
		return nil, fmt.Errorf("每分钟仅能发送一次")
	}

	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(Intn))
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf("短信验证失败")
	}
	redis.Client.Set("sendSms"+in.Mobile+in.Source, Intn, time.Minute*5)

	redis.Client.Set("sendSmsMinute"+in.Mobile+in.Source, "1", time.Minute*5)

	return &yktworpc.SendSmsResponse{}, nil
}
